package p.ithorns.framework.minio;

import com.google.common.collect.Sets;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import p.ithorns.framework.minio.model.UploadException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * MinioTemplate
 *
 * @author liuhaitao
 * @date 2024/4/7 10:15
 * @since 1.0.0
 */
public class MinioTemplate {

    private final static Logger log = LoggerFactory.getLogger(MinioTemplate.class);

    private final MinioClient client;

    public MinioTemplate(MinioClient client) {
        this.client = client;
    }

    /**
     * 创建Bucket
     *
     * @param bucketName 存储桶名称
     * @author 2024/04/07 $time$ by Ht.L
     */
    public void createBucket(String bucketName) throws Exception {
        if (existsBucket(bucketName)) {
            MakeBucketArgs args = MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build();
            client.makeBucket(args);
        }
    }

    /**
     * 是否存在bucket
     *
     * @param bucketName 存储桶名称
     * @return boolean
     * @author 2024/04/07 by Ht.L
     */
    public boolean existsBucket(String bucketName) throws Exception {
        BucketExistsArgs args = BucketExistsArgs.builder()
                .bucket(bucketName)
                .build();
        return client.bucketExists(args);
    }

    /**
     * 获取存储桶策略
     *
     * @param bucketName 存储桶名称
     * @return {@link String }
     * @author Ht.L on 2024/04/07
     */
    public String getBucketPolicy(String bucketName) throws Exception {
        GetBucketPolicyArgs args = GetBucketPolicyArgs.builder()
                .bucket(bucketName)
                .build();
        return client.getBucketPolicy(args);
    }

    /**
     * 获得所有Bucket列表
     *
     * @return List<Bucket>
     */
    public List<Bucket> getAllBuckets() throws Exception {
        return client.listBuckets();
    }

    /**
     * 根据bucketName获取其相关信息
     *
     * @param bucketName 存储桶名称
     * @return Optional<Bucket>
     */
    public Optional<Bucket> getBucket(String bucketName) throws Exception {
        return getAllBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
    }

    /**
     * 根据bucketName删除Bucket，true：删除成功； false：删除失败，文件或已不存在
     *
     * @param bucketName 存储桶名称
     */
    public void removeBucket(String bucketName) throws Exception {
        client.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
    }

    /**
     * 判断文件是否存在
     *
     * @param bucketName 存储桶名称
     * @param objectName 对象名
     * @return boolean
     */
    public boolean isObjectExist(String bucketName, String objectName) {
        boolean exist = true;
        try {
            client.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            log.error("[Minio工具类]>>>> 判断文件是否存在, 异常：", e);
            exist = false;
        }
        return exist;
    }

    /**
     * 判断文件夹是否存在
     *
     * @param bucketName 存储桶名称
     * @param objectName 对象名
     * @return boolean
     */
    public boolean isFolderExist(String bucketName, String objectName) {
        boolean exist = false;
        try {
            Iterable<Result<Item>> results = client.listObjects(
                    ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(false).build());
            for (Result<Item> result : results) {
                Item item = result.get();
                if (item.isDir() && objectName.equals(item.objectName())) {
                    exist = true;
                }
            }
        } catch (Exception e) {
            log.error("[Minio工具类]>>>> 判断文件夹是否存在，异常：", e);
            exist = false;
        }
        return exist;
    }

    /**
     * 根据文件前置查询文件
     *
     * @param bucketName 存储桶名称 存储桶
     * @param prefix     前缀
     * @param recursive  是否使用递归查询
     * @return MinioItem 列表
     */
    public List<Item> getAllObjectsByPrefix(String bucketName,
                                            String prefix,
                                            boolean recursive) throws Exception {
        List<Item> list = new ArrayList<>();
        Iterable<Result<Item>> objectsIterator = client.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
        if (objectsIterator != null) {
            for (Result<Item> o : objectsIterator) {
                Item item = o.get();
                list.add(item);
            }
        }
        return list;
    }

    /**
     * 获取文件流
     *
     * @param bucketName 存储桶名称 存储桶
     * @param objectName 文件名
     * @return 二进制流
     */
    public InputStream getObject(String bucketName, String objectName) throws Exception {
        return client.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
    }

    /**
     * 断点下载
     *
     * @param bucketName 存储桶
     * @param objectName 文件名称
     * @param offset     起始字节的位置
     * @param length     要读取的长度
     * @return 二进制流
     */
    public InputStream getObject(String bucketName, String objectName, long offset, long length)
            throws Exception {
        return client.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .offset(offset)
                        .length(length)
                        .build());
    }

    /**
     * 获取路径下文件列表
     *
     * @param bucketName 存储桶
     * @param prefix     文件名称
     * @param recursive  是否递归查找，false：模拟文件夹结构查找
     * @return 二进制流
     */
    public Iterable<Result<Item>> listObjects(String bucketName, String prefix, boolean recursive) {
        return client.listObjects(
                ListObjectsArgs.builder()
                        .bucket(bucketName)
                        .prefix(prefix)
                        .recursive(recursive)
                        .build());
    }

    /**
     * 使用MultipartFile进行文件上传
     *
     * @param bucketName  存储桶
     * @param objectName  对象名
     * @param contentType 类型
     * @param file        文件名
     * @return ObjectWriteResponse
     */
    public ObjectWriteResponse uploadFile(String bucketName, String objectName,
                                          String contentType, MultipartFile file) throws Exception {
        try (InputStream inputStream = file.getInputStream()) {
            return this.uploadFile(bucketName, objectName, contentType, inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public ObjectWriteResponse uploadFile(String bucketName, String objectName,
                                          String contentType, InputStream inputStream)
            throws Exception {
        if (!existsBucket(bucketName)) {
            log.warn("Bucket[{}] not exists! Create it now.", bucketName);
            createBucket(bucketName);
        }

        try {
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    // object是存储对象，可表示文件名称，也可以是多层级目录 如 'a/b/c/d.txt'
                    .object(objectName)
                    .contentType(contentType)
                    .stream(inputStream, inputStream.available(), -1)
                    .build();
            return client.putObject(args);
        } catch (Exception e) {
            throw new UploadException(e);
        }

    }

    /**
     * 图片上传
     *
     * @param bucketName  -存储桶名称
     * @param imageBase64 -图片base64
     * @param imageName   -图片名称
     * @return ObjectWriteResponse
     */
    public ObjectWriteResponse uploadImage(String bucketName, String imageBase64, String imageName)
            throws Exception {
        if (StringUtils.hasText(imageBase64)) {
            InputStream in = base64ToInputStream(imageBase64);
            String newName = System.currentTimeMillis() + "_" + imageName + ".jpg";

            LocalDate now = LocalDate.now();
            String year = String.valueOf(now.getYear());
            String month = String.valueOf(now.getMonth());
            return uploadFile(bucketName, year + "/" + month + "/" + newName, in);
        }
        return null;
    }


    /**
     * base64转输入流
     *
     * @param base64 -文件base64
     * @return {@link InputStream }
     * @author Ht.L on 2024/04/07
     */
    public static InputStream base64ToInputStream(String base64) {
        ByteArrayInputStream stream = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64.trim());
            // byte[] bytes = new BASE64Decoder().decodeBuffer(base64.trim());
            stream = new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stream;
    }


    /**
     * 上传本地文件
     *
     * @param bucketName 存储桶
     * @param objectName 对象名称
     * @param fileName   本地文件路径
     * @return ObjectWriteResponse
     */
    public ObjectWriteResponse uploadFile(String bucketName, String objectName, String fileName)
            throws Exception {
        return client.uploadObject(
                UploadObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .filename(fileName)
                        .build());
    }

    /**
     * 通过流上传文件
     *
     * @param bucketName  存储桶
     * @param objectName  文件对象
     * @param inputStream 文件流
     * @return ObjectWriteResponse
     */
    public ObjectWriteResponse uploadFile(String bucketName, String objectName, InputStream inputStream)
            throws Exception {
        return client.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(inputStream, inputStream.available(), -1)
                        .build());
    }

    /**
     * 创建文件夹或目录
     *
     * @param bucketName 存储桶
     * @param objectName 目录路径
     * @return ObjectWriteResponse
     */
    public ObjectWriteResponse createDir(String bucketName, String objectName) throws Exception {
        return client.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(new ByteArrayInputStream(new byte[]{}), 0, -1)
                        .build());
    }

    /**
     * 获取文件信息, 如果抛出异常则说明文件不存在
     *
     * @param bucketName 存储桶
     * @param objectName 文件名称
     * @return String
     */
    public String getObjectStatus(String bucketName, String objectName) throws Exception {
        return client.statObject(
                        StatObjectArgs.builder()
                                .bucket(bucketName)
                                .object(objectName)
                                .build()
                )
                .toString();
    }

    /**
     * 拷贝文件
     *
     * @param bucketName    存储桶
     * @param objectName    文件名
     * @param srcBucketName 目标存储桶
     * @param srcObjectName 目标文件名
     */
    public ObjectWriteResponse copy(String bucketName, String objectName, String srcBucketName, String srcObjectName)
            throws Exception {
        return client.copyObject(
                CopyObjectArgs.builder()
                        .source(CopySource.builder().bucket(bucketName).object(objectName).build())
                        .bucket(srcBucketName)
                        .object(srcObjectName)
                        .build());
    }

    /**
     * 删除文件
     *
     * @param bucketName 存储桶
     * @param objectName 文件名称
     */
    public void remove(String bucketName, String objectName) throws Exception {
        client.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
    }

    /**
     * 批量删除文件
     *
     * @param bucketName 存储桶
     * @param keys       需要删除的文件列表
     */
    public void removeMulti(String bucketName, List<String> keys) {
        List<DeleteObject> objects = keys.stream()
                .map(DeleteObject::new)
                .collect(Collectors.toList());

        RemoveObjectsArgs args = RemoveObjectsArgs.builder()
                .bucket(bucketName)
                .objects(objects)
                .build();

        client.removeObjects(args);
    }

    /**
     * 获取文件外链
     *
     * @param bucketName 存储桶
     * @param objectName 文件名
     * @param expires    过期时间 <=7 秒 （外链有效时间（单位：秒））
     * @return url
     */
    public String getObjectUrl(String bucketName, String objectName, Integer expires) throws Exception {
        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder().expiry(expires).bucket(bucketName).object(objectName).build();
        return client.getPresignedObjectUrl(args);
    }

    /**
     * 获得文件外链
     *
     * @param bucketName -存储桶名称
     * @param objectName -对象名称
     * @return url
     */
    public String getObjectUrl(String bucketName, String objectName) throws Exception {
        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .method(Method.GET).build();
        return client.getPresignedObjectUrl(args);
    }

    /**
     * 将URLDecoder编码转成UTF8
     *
     * @param str -
     * @return String
     * @throws UnsupportedEncodingException -
     */
    public String getUtf8ByURLDecoder(String str) throws UnsupportedEncodingException {
        if (StringUtils.hasText(str)) {
            String url = str.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            return URLDecoder.decode(url, "UTF-8");
        }
        return "";
    }


    private final String TEMP_FILE_PREFIX = "temp";

    /**
     * 分片上传
     *
     * @param file  文件
     * @param index 分片索引
     * @param total 切片总数
     * @param md5   整体文件MD5
     * @author Ht.L on 2024/04/07
     */
    public void uploadFileInChunks(MultipartFile file, Integer index, Integer total, String md5) throws Exception {
        String fileName = file.getName();
        // 将文件minio临时目录
        if (existsBucket(TEMP_FILE_PREFIX)) {
            createBucket(TEMP_FILE_PREFIX);
        }

        // 检查还需要上传的文件序号
        Iterable<Result<Item>> results = listObjects(TEMP_FILE_PREFIX, fileName, false);
        Set<String> uploadedObjNames = Sets.newTreeSet();
        for (Result<Item> result : results) {
            uploadedObjNames.add(result.get().objectName());
        }
    }


}